﻿var MessageBox = {
    close: function () {
        //var layerObj = $('.xubox_layer');
        var layerObj = $('.layui-layer');
        $.each(layerObj, function () {
            var i = $(this).attr('times');
            layer.close(i);
        });
    },
    open: function (html, x, y, w, h) {
        layer.open({
            type: 1,   //0-4的选择,（1代表page层）
            area: [w, h],
            fix: false,
            shade: [0],  //不显示遮罩
            border: [11, 0.5, '#838383'], //不显示边框
            offset: [x, y],
            title: false,
            bgcolor: '#fff', //设置层背景色
            //shade: [0.5, '#fff'],//遮罩区域
            //shadeClose: true,//用来控制点击遮罩区域是否关闭层
            //page: { html: html }
            content: html
        });
    },
    //向下弹出对话框
    uderTips: function (obj, html, width) {
        if (!width) {
            width = 200;
        }
        layer.tips(html, obj, {
            guide: 2,
            time: 3,
            style: ['background-color:#0FA6D8; color:#fff', '#0FA6D8'],
            maxWidth: width
        });
    },
    loading: function (txt) {
        layer.load(txt);
    }
}

//首页
var Home = {
    //头部导航栏
    initTopNav: function () {
        this.navHover();
        var pathMap = {
            "/home/index": 0,
            "/home": 0,
            "/": 0,
            "/home/querygameinfolist": 0,
            "/home/querygiftbag": 0,
            "/home/mygame": 1,
            "/home/playermall": 2,
            "/pay/index": 3,
            "/pay": 3,
            "/home/chargeevents": 3,
            "/pay/exchangetogamecurrency": 3
        }

        var path = document.location.pathname.toLowerCase();
        var index = pathMap[path];
        var p_nav = parseInt(Player.topTabs[path]);

        if (!isNaN(p_nav)) {
            index = 1;
        }

        var html = "";
        switch (parseInt(index)) {
            case 0:
                html += '<div class="nav1"><a href="/home/index" class="cur01">发现游戏</a></div>';
                html += '<div class="nav2">';
                html += '<div class="wrapper">';
                html += '<ul class="nav01">';
                if (path == '/' || path == '/home' || path == '/home/index') {
                    html += '<li><a href="/home/index" class="cur02">热门游戏</a></li>';
                } else {
                    html += '<li><a href="/home/index">热门游戏</a></li>';
                }
                if (path == '/home/querygameinfolist') {
                    html += '<li><a href="/home/querygameinfolist" class="cur02">游戏分类</a></li>';
                } else {
                    html += '<li><a href="/home/querygameinfolist">游戏分类</a></li>';
                }
                if (path == '/home/querygiftbag') {
                    html += '<li><a href="/home/querygiftbag" class="cur02">游戏礼包</a></li>';
                } else {
                    html += '<li><a href="/home/querygiftbag">游戏礼包</a></li>';
                }
                html += '</ul>';
                html += '</div>';
                html += '</div>';
                html += '<span></span>';

                break;
            case 1:
                html += '<div class="nav1"><a href="/home/mygame" class="cur01">我的CNWAN</a></div>';
                html += '<span></span>';
                break;
            case 2:
                html += '<div class="nav1"><a href="/home/playermall" class="cur01">积分商城</a></div>';
                html += '<span></span>';
                break;
            case 3:
                html += '<div class="nav1"><a href="/pay" class="cur01">充值游戏</a></div>';
                html += '<div class="nav2 nav3">';
                html += '<div class="wrapper">';
                html += '<ul class="nav01">';
                if (path == '/pay' || path == "/pay/index") {
                    html += '<li><a href="/pay" class="cur02">充值</a></li>';
                } else {
                    html += '<li><a href="/pay">充值</a></li>';
                }
                if (path == '/home/chargeevents') {
                    html += '<li><a href="/home/chargeevents" class="cur02">充值活动</a></li>';
                } else {
                    html += '<li><a href="/home/chargeevents">充值活动</a></li>';
                }
                if (path == '/pay/exchangetogamecurrency') {
                    html += '<li><a href="/pay/exchangetogamecurrency" class="cur02">兑换游戏币</a></li>';
                } else {
                    html += '<li><a href="/pay/exchangetogamecurrency">兑换游戏币</a></li>';
                }
                html += '</ul>';
                html += '</div>';
                html += '</div>';
                html += '<span></span>';
                break;
            default:
                break;
        }

        $(".top_item").eq(index).html(html);
    },
    navHover: function () {
        $(".top_item").bind("mouseenter", function () {
            $(this).children('.nav2').show();
            $(this).siblings().children('.nav2').hide();
        });
    },
    //打开消息面板
    openMessagePanel: function () {
        var box = $("#p_msg");
        var arrow = $(".r_ind_show2");
        $("#p_set").slideUp(function () { $(".r_ind_show1").hide(); });

        $(document).unbind("click");
        if (!box.is(":hidden")) {
            box.slideUp('fast', function () { arrow.hide(); });
            return false;
        }
        //重新初始化角标
        Home.initMessageCount();
        $.post("/Home/GetMessageNotice", function (result) {
            if (result) {
                var html = '<ul>';
                for (var i = 0; i < result.length; i++) {
                    if (result[i].Type == "SITE") {
                        html += '<li>'
                        html += result[i].Prefix;
                        html += result[i].Title;
                        html += '</li>';
                    } else if (result[i].Type == "BOARD") {
                        html += '<li>'
                        html += result[i].Prefix;
                        html += '<a href="/Home/OtherMessageBoard?PlayerID=' + result[i].SenderID + '" class="blue">';
                        html += result[i].SenderName;
                        html += '</a>给你 ';
                        html += '<a href="/Home/MessageBoard" class="blue">';
                        html += result[i].Count;
                        html += '留言</a>。</li>';
                    }
                }

                html += '</ul>';
                if (result.length <= 0) {
                    html += '<ul class="ml20" style="color:gray;">最近没有收到新消息...</ul>';
                } else {
                    html += '<input type="button" value="查看全部" class="fl gy_btn6 gy_btn8 round ml20 mt15" onclick="window.location.href=\'/home/PlayerMessageNotice\'" />';
                }

                box.html(html);
                arrow.show(0, function () {
                    box.slideDown('fast');
                });

                $(document).bind("click", function () {
                    Home.openMessagePanel();
                });
            }
        });
    },
    //打开个人设置面板
    openSetPanel: function () {
        var box = $("#p_set");
        var arrow = $(".r_ind_show1");
        $("#p_msg").slideUp(function () { $(".r_ind_show2").hide(); });

        $(document).unbind("click");
        if (!box.is(":hidden")) {
            box.slideUp(function () { arrow.hide(); });
            return false;
        } else {
            arrow.show(0, function () {
                box.slideDown();
            });
        }

        setTimeout(function () {
            $(document).bind("click", function () {
                Home.openSetPanel();
            });
        }, 0);
    },
    //初始化消息条数
    initMessageCount: function () {
        Home.showMessageCount();
        var timer = setInterval(function () {
            Home.showMessageCount(timer);
        }, 20000);
    },
    //显示信息消息条数
    showMessageCount: function (timer) {
        $.post("/Home/GetNoticeCount", function (result) {
            if (!isNaN(result)) {
                if (parseInt(result) > 0) {
                    $("#m_count").html(result);
                    $("#m_count").show();
                }
                else {
                    $("#m_count").hide();
                }

            } else {
                $("#m_count").hide();
            }
        });
    }
}

var Game = {
    play: function (gid, id) {
        var x = $(id).offset().top - $(document).scrollTop() + 35 + "px";
        var y = $(id).offset().left + 'px';
        $.post("/common/queryserver", { gameID: gid }, function (result) {
            var html = '';
            if (result) {
                for (var i = 0; i < result.length; i++) {
                    html += '<a href="/home/logingame?gameid=' + gid + '&serverid=' + result[i].GameServerID + '">' + result[i].Name + '</a><br/>';
                }
                if (result.length > 0) {
                    MessageBox.uderTips(id, html, 200);
                } else {
                    alert("该游戏未配置服务器");
                }
            }
        });
    },
    //加载玩家信息
    loadPlayInfo: function () {
        var roles = $(".gamerole");
        if (roles) {
            $.each(roles, function (index, value) {
                var gameid = $(value).children().eq(0).attr("gameid");
                var serverid = $(value).children().eq(0).attr("serverid");
                var pid = $(value).children().eq(0).attr("pid");
                var flag = true;
                $.ajax({
                    type: "POST",
                    dataType: "JSON",
                    url: "/Home/QueryPlayerGameFromMaker",
                    data: { gameID: gameid, serverID: serverid, playerID: pid },
                    success: function (result) {
                        if (result) {
                            $(value).children().eq(1).html('角色：' + (result.Name == null ? "" : result.Name));
                            $(value).children().eq(2).html('等级：' + (result.LevelInfo == null ? "" : result.LevelInfo));
                            $(value).children().eq(3).html('阵营：' + (result.KingdomName == null ? "" : result.KingdomName));
                            flag = false;
                        }
                    }
                });
                var min = new Date().getMinutes() + 10;
                while (new Date().getMinutes < min) {
                    if (flag == false) {
                        min = new Date().getMinutes() - 10;
                    }
                }
            });
        }
    }
}


//分页
var Paging = {
    generatorPage: function (rowCount, curPage, pageCount) {
        var html = '';
        if (parseInt(rowCount) <= 0) {
            html += '<div class="page_content">暂时没有找到相关记录哦~</div>';
            $("#table_container").append(html);
            return false;
        }

        rowCount = parseInt(rowCount);
        curPage = parseInt(curPage);
        pageCount = parseInt(pageCount);

        html += '<div class="page_list">';
        html += '<p>共 ' + rowCount + ' 条记录，' + pageCount + '页</p><ul>';

        var startPage
        if (curPage > 5) {
            startPage = curPage - 4
        } else {
            startPage = 1
        }

        if (curPage == 1) {
            html += '<li><a href="javascript:void(0);">&lt;</a></li>';
        } else {
            html += '<li><a href="javascript:void(0);" onclick="Paging.setCurrentPage(\'' + (curPage - 1) + '\')">&lt;</a></li>';
        }
        for (var i = startPage; i <= pageCount; i++) {
            if (curPage == i) {
                html += '<li><a href="javascript:void(0);" class="cur">' + i + '</a></li>';
            } else if (i <= startPage + 9) {
                html += '<li><a href="javascript:void(0);" onclick="Paging.setCurrentPage(\'' + i + '\')">' + i + '</a></li>';
            } else {
                break;
            }
        }
        if (rowCount == 0) {
            html += '<li><a href="javascript:void(0);" class="cur">1</a></li>';
        }

        if (curPage >= pageCount) {
            html += '<li><a href="javascript:void(0);">&gt;</a></li>';
        } else {
            html += '<li><a href="javascript:void(0);" onclick="Paging.setCurrentPage(\'' + (curPage + 1) + '\')">&gt;</a></li></ul>';
        }

        html += '</div>';

        $("#table_container").append(html);
    },
    setCurrentPage: function (cur) {
        $("#curPage").val(cur);
        $("#form1").submit();
    },
    submit: function (pageIndex) {
        $("#curPage").val(pageIndex);
        $("#form1").submit();
    },
    //生成短页码
    simplePage: function (curRowSize, curPage, pageCount) {
        var html = '';
        curRowSize = parseInt(curRowSize);
        curPage = parseInt(curPage);
        pageCount = parseInt(pageCount);

        if (curRowSize <= 0 & pageCount <= 0) {
            html += '<div class="page_content">暂时没有找到相关记录哦~</div>';
            $("#form_container").append(html);
            return false;
        }

        html += '<div class="fl page ptb" id="page">';

        if (curPage == 1 && pageCount == 1) {

        } else if (curPage == pageCount && pageCount > 1) {
            html += '<a href="javascript:Paging.submit(' + (curPage - 1) + ');" class="pre01"></a>';
            //html += '<a href="javascript:void(0);" onclick="alert(\'已经是最后一页咯~\');" class="next01"></a>';
        } else if (curPage == 1 && pageCount > 1) {
            //html += '<a href="javascript:void(0);" onclick="alert(\'已经是第一页咯~\');" class="pre01"></a>';
            html += '<a href="javascript:Paging.submit(' + (curPage + 1) + ');" class="next01"></a>';
        } else {
            html += '<a href="javascript:Paging.submit(' + (curPage - 1) + ');" class="pre01"></a>';
            html += '<a href="javascript:Paging.submit(' + (curPage + 1) + ');" class="next01"></a>';
        }

        html += '</div>';
        $("#form_container").append(html);
    }

}

//玩家信息
var Player = {
    sign: function () {
        $.post("/home/playersign", function (result) {
            if (result.Success) {
                $("#pSign").val("已签到 +" + result.Value);
                var inte = $.trim($("#pInte").html());
                var intePlus = parseInt(inte) + parseInt(result.Value);
                $("#pInte").html(intePlus);
            } else {
                $("#pSign").unbind("click");
            }
        });
    },
    uploadAvatar: function () {
        MessageBox.loading("正在上传...");
        $.ajaxFileUpload({
            url: '/home/playeruploadavatar',
            secureuri: false,
            fileElementId: 'avafile',
            type: 'POST',
            dataType: 'content',
            success: function (result) {
                MessageBox.close();
                result = eval('(' + result + ')');
                if (result.Success) {
                    $("#avaPath").attr('src', result.FilePath);
                    $("[name='AvatarPath']").val(result.FilePath);
                } else {
                    alert(result.Info);
                }
            },
            error: function (html, status, e) {
                MessageBox.close();
                alert(status);
            }
        });
    },
    //选择省份
    chooseAdr: function (pID, cID) {
        if (pID == undefined || pID == "" || pID == null) {
            pID = "1";
        }
        var html = '<div class="fl resident mycount1_bk"><h3>中国大陆</h3><div class="fl resident_list eage2">';
        var x = ($("#account1_address").offset().top - $(document).scrollTop() + 35) + "px";
        var y = $("#account1_address").offset().left + 'px';

        $.post("/common/queryprovinces", function (result) {
            if (result.length > 0) {
                for (var i = 0; i < result.length; i++) {
                    html += '<a href="javascript:Player.chooseCtiy(\'' + result[i].AddressID + '\',\'' + result[i].Name + '\');">' + result[i].Name + '</a>';
                }
                html += '</div></div>';
                MessageBox.close();//先关闭当前弹窗，再打开一个新的弹窗
                MessageBox.open(html, x, y, '400px', '300px');
            }
        });
    },
    //选择所属市
    chooseCtiy: function (pID, pName) {
        var html = '<div class="fl resident mycount1_bk"><h3>' + pName + '</h3><div class="fl resident_list eage2">';
        var x = ($("#account1_address").offset().top - $(document).scrollTop() + 35) + "px";
        var y = $("#account1_address").offset().left + 'px';

        $.post("/common/querydistricts", { parentID: pID }, function (data) {
            if (data.length > 0) {
                for (var j = 0; j < data.length; j++) {

                    html += '<a href="javascript:Player.setAddress(\'' + pID + '\',\'' + data[j].AddressID + '\');">' + data[j].Name + '</a>';
                }

                html += '</div></div>';
                MessageBox.close();//先关闭当前弹窗，再打开一个新的弹窗
                MessageBox.open(html, x, y, '400px', '300px');
            }
        });
    },
    setAddress: function (pID, cID) {
        $.post("/common/queryaddress", { id: pID }, function (result) {
            if (result) {
                $("[name='ProvinceID']").val(result.AddressID);
                $.post("/common/queryaddress", { id: cID }, function (data) {
                    if (data) {
                        $("[name='DistrictID']").val(data.AddressID);
                        $("#addrInfo").html(result.Name + "  " + data.Name);
                        MessageBox.close();
                    }
                });
            }
        });
    },
    chooseAge: function () {
        var html = '<div class="fl mycount1_bk"><div class="fl age_list">';
        var arr = new Array('神童', '00后', '90后', '80后', '70后', '60后', '50后', '40后', '化石');
        for (var i = 0; i < arr.length; i++) {
            html += '<a href="javascript:Player.setAge(\'' + arr[i] + '\');">' + arr[i] + '</a>';
        }
        html += '</div></div>';
        var x = ($("#account1_age").offset().top - $(document).scrollTop() + 35) + "px";
        var y = $("#account1_age").offset().left + 'px';
        MessageBox.close();
        MessageBox.open(html, x, y, '400px', '80px');
    },
    setAge: function (name) {
        $("[name='Age']").val(name);
        $("#ageInfo").html(name);
        MessageBox.close();
    },
    chooseStar: function () {
        var arr = new Array('白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '魔羯座', '水瓶座', '双鱼座');
        var date = new Array('3.21-4.19', '4.20-5.20', '5.21-6.21', '6.22-7.22', '7.23-8.22', '8.23-9.22', '9.23-10.23', '10.24-11.22', '11.23-12.21', '12.22-1.19', '1.20-2.18', '2.19-3.20');
        var cls = new Array('', 'jn', 'sz', 'jx', 'sz', 'cn', 'tp', 'tx', 'ss', 'mj', 'sp', 'sy');
        var html = '<div class="fl mycount1_bk"><div class="fl constellation_list"><ul>';
        for (var i = 0; i < arr.length; i++) {
            html += '<li onclick="Player.setStar(\'' + arr[i] + '\');"><span class="' + cls[i] + '"></span>';
            html += '<div class="xz_content"><p>' + arr[i] + '</p><p>' + date[i] + '</p></div></li>';
        }
        html += '</ul></div></div>';

        var x = ($("#account1_constellation").offset().top - $(document).scrollTop() + 35) + "px";
        var y = $("#account1_constellation").offset().left + 'px';
        MessageBox.close();
        MessageBox.open(html, x, y, '500px', '260px');
    },
    setStar: function (name) {
        $("[name='StarSign']").val(name);
        $("#starInfo").html(name);
        MessageBox.close();
    },
    chooseIncome: function () {
        var html = '<div class="fl mycount1_bk"><div class="fl age_list">';
        var arr = new Array('2K以下', '2K~5K', '5K~8K', '8K~12K', '12K~20K', '20K以上', '不用赚钱');
        for (var i = 0; i < arr.length; i++) {
            html += '<a href="javascript:Player.setIncome(\'' + arr[i] + '\');">' + arr[i] + '</a>';
        }
        html += '</div></div>';

        var x = ($("#account1_income").offset().top - $(document).scrollTop() + 35) + "px";
        var y = $("#account1_income").offset().left + 'px';
        MessageBox.close();
        MessageBox.open(html, x, y, '400px', '80px');
    },
    setIncome: function (name) {
        $("[name='Income']").val(name);
        $("#incomeInfo").html(name);
        MessageBox.close();
    },
    chooseMyKey: function () {
        var arr = new Array('P民', '屌丝', '潇洒哥', '剩斗士', '暖男', '杀马特', '富二代', '土豪', '白富美', '御姐', '女神', '战神', '职业高手');
        var html = '<div class="fl mycount1_bk"><div class="fl age_list">';
        for (var i = 0; i < arr.length; i++) {
            html += '<a href="javascript:Player.setMykey(\'' + arr[i] + '\')">' + arr[i] + '</a>';
        }
        html += '</div></div>';

        var x = ($("#account1_mykey").offset().top - $(document).scrollTop() + 35) + "px";
        var y = $("#account1_mykey").offset().left + 'px';
        MessageBox.close();
        MessageBox.open(html, x, y, '400px', '80px');
    },
    setMykey: function (name) {
        $("[name='MyKey']").val(name);
        $("#mykeyInfo").html(name);
        MessageBox.close();
    },
    topTabs: {
        "/home/mygame": 0,
        "/home/myrecharge": 1,
        "/home/myrechargerecord": 1,
        "/home/playerinfo": 2,
        "/home/accountsafe": 2,
        "/home/playerintegralrecord": 2,
        "/home/myevent": 3,
        "/home/myeventrecord": 3,
        "/home/playergiftbag": 4,
        "/home/playerproduct": 5,
        "/home/playermessagenotice": 6,
        "/home/messageboard": 7
    }
}

var Pay = {
    payRate: undefined,//支付费率
    gameRate: undefined,//
    toCnwan: true,
    discount: 0,//折扣
    targetAccount: undefined,
    //选择游戏
    chooseGame: function () {

        var html = '<div class="fl resident mycount1_bk" style="width:100%;"><h3>请选择游戏</h3><div class="fl resident_list">';
        $.post("/common/querygames", function (result) {
            if (result) {
                for (var i = 0; i < result.length; i++) {
                    html += '<a href="javascript:Pay.chooseServer(\'' + result[i].GameID + '\',\'' + result[i].Name + '\');">' + result[i].Name + '</a>';
                }
                html += '</div></div>';
                var x = ($("#gameSet").offset().top - $(document).scrollTop() + 35) + "px";
                var y = $("#gameSet").offset().left + 'px';
                MessageBox.close();
                MessageBox.open(html, x, y, '550px', '400px');
            }
        });
    },

    //选择服务器
    chooseServer: function (gid, gname) {
        var html = '<div class="fl resident mycount1_bk" style="width:100%;"><h3>请选择服务器 (游戏: ' + gname + ')</h3><div class="fl resident_list">';
        $.post("/common/queryserver", { gameID: gid }, function (data) {
            if (data != undefined && data != null && data != "") {
                for (var i = 0; i < data.length; i++) {
                    html += '<a href="javascript:Pay.setGameInfo(\'' + gid + '\',\'' + data[i].GameServerID + '\');">' + data[i].Name + '</a>';
                }

                html += '</div></div>';
                var x = ($("#gameSet").offset().top - $(document).scrollTop() + 35) + "px";
                var y = $("#gameSet").offset().left + 'px';
                MessageBox.close();
                MessageBox.open(html, x, y, '550px', '400px');
            } else {
                Pay.setNoServerInfo(gid);
            }
        });
    },
    //设置游戏信息
    setGameInfo: function (gid, sid) {
        $.post("/common/querygame", { gameID: gid }, function (result) {
            if (result) {
                //设置游戏币兑换比例
                Pay.gameRate = result.ExchangeRate;
                Pay.showRatio();

                //设置兑换表单信息
                Pay.setExchangeForm(result.GameID, result.Name, result.GameCurrencyUnit, result.ExchangeRate);
                Pay.initAmountList();//初始化金额列表

                var info = result.Name + "   ";

                $.post("/common/queryserverbyid", { serverID: sid }, function (data) {
                    if (data) {
                        $("[name='ServerID']").val(data.GameServerID);
                        $("[name='ServerName']").val(data.Name);
                        info += data.Name;
                        $("#gameSet").children("a").html(info);
                        MessageBox.close();
                    }
                });
            }
        });
    },
    //设置游戏信息
    setNoServerInfo: function (gid) {
        $.post("/common/querygame", { gameID: gid }, function (result) {
            if (result) {
                //设置游戏币兑换比例
                Pay.gameRate = result.ExchangeRate;
                Pay.showRatio();

                //设置兑换表单信息
                Pay.setExchangeForm(result.GameID, result.Name, result.GameCurrencyUnit, result.ExchangeRate);
                Pay.initAmountList();//初始化金额列表

                var info = result.Name;
                $("[name='ServerID']").val('');
                $("[name='ServerName']").val('');
                $("#gameSet").children("a").html(info);
                MessageBox.close();
            }
        });
    },
    //选择购买数量
    chooseBuyAmount: function (amount, other) {
        Pay.getDiscount();
        $("[name='OtherAmount']").val("");
        if (Pay.validGameInfo()) {
            $("[flag='amountMsg']").html("");
            var exchangeRate = $("[name='ExchangeRate']").val();
            if (exchangeRate != null && exchangeRate != undefined) {
                var total;
                if (Pay.toCnwan) {
                    //total = (Pay.exchangeAmount() * amount).toFixed(0);
                    total = parseInt(Pay.exchangeAmount() * amount);
                } else {
                    //total = Math.round(Pay.exchangeAmount() * amount);
                    total = parseInt(Pay.exchangeAmount() * amount);
                }

                $("[name='GameCurrencyAmount']").val(total);
                $("#exAmount").html(total);
            }
        }
    },
    //金额change事件
    changeAmount: function (obj) {
        var exchangeRate = $("[name='ExchangeRate']").val();
        var val = $.trim($(obj).val());
        if (val.length <= 0) {
            $("#exAmount").html("");
            $("[flag='amountMsg']").html("");
            return false;
        }

        var amount = parseInt(val);

        if (/^[1-9]\d*$/.test(amount) == false) {
            $("[flag='amountMsg']").html("请输入(10-50000)之间的整数");
        } else if (amount < 10 || amount > 50000) {
            $("[flag='amountMsg']").html("请输入(10-50000)之间的整数");
        } else {
            $("[flag='amountMsg']").html("");
            var total;
            if (Pay.toCnwan) {
                //total = (Pay.exchangeAmount() * amount).toFixed(0);
                total = parseInt(Pay.exchangeAmount() * amount);
            } else {
                //total = Math.round(Pay.exchangeAmount() * amount);
                total = parseInt(Pay.exchangeAmount() * amount);
            }

            $("[name='GameCurrencyAmount']").val(total);
            $("[name='BuyAmount']").val(amount);
            if (isNaN(total)) {
                $("#exAmount").html('');
            } else {
                $("#exAmount").html(total);
            }
        }
    },
    bankMap: {
        "ICBC": "bank_101", "CMB": "bank_201", "CCB": "bank_301", "ABC": "bank_401",
        "CITIC": "bank_501", "CEB": "bank_701", "SPDB": "bank_601", "SDB": "bank_801",
        "COMM": "bank_1101", "BOC": "bank_1201", "CEB": "bank_c01", "CIB": "bank_c02",
        "CMBC": "bank_901", "GDB": "bank_1001", "PAB": "bank_2001", "SHRCB": "bank_1501",
        "SRCB": "bank_1601", "NBCB": "bank_1701", "NBCB": "bank_1801", "BOB": "bank_1901"
    },
    payType: {
        "03": 1, "19": 2, "60": 3, "77": 4, "76": 5, "66": 6, "63": 7, "75": 8
    },
    gameShow: function () {
        $("[name='OtherAmount']").val("");
        $("[flag='amountMsg']").html("");
        $("#gameArea").show();
        Pay.resetChangeInfo();
        Pay.toCnwan = false;
    },
    gameHide: function () {
        $("[name='OtherAmount']").val("");
        $("[flag='amountMsg']").html("");
        $("#gameArea").hide();
        Pay.gameRate = 1;
        Pay.toCnwan = true;
        Pay.resetChangeInfo();
        //设置兑换表单信息
        Pay.setExchangeForm("", "", "CN币", 1);
        Pay.showRatio();
    },
    preprocess: function () {
        $.post("/pay/preprocessorder", $("#form1").serialize(), function (result) {
            if (result) {
                if (result.Success) {
                    var html = '<div class="order shadow2"><div class="order_bt"><h3><b>确认充值订单</b><a href="javascript:void(0);" onclick="MessageBox.close();"></a></h3></div><table width="560" cellspacing="0" border="0" class="ml20"><tbody>';
                    html += '<tr><td width="150" class="pl55">充值方式：</td><td width="406">' + result.RechargeModeName + '</td></tr>';
                    html += '<tr><td width="150" class="pl55">充值帐号：</td><td width="406">' + result.TargetAccount + '</td></tr>';
                    html += '<tr><td width="150" class="pl55">支付方式：</td><td width="406">' + result.PayModeName + '</td></tr>';
                    html += '<tr><td width="150" class="pl55">支付银行：</td><td width="406">' + result.PayInstitutionName + '</td></tr>';
                    html += '<tr><td width="150" class="pl55">支付金额：</td><td width="406">￥' + result.BuyAmount + '</td></tr>';
                    html += '<tr><td width="150" class="pl55">充值游戏：</td><td width="406">' + result.GameName + '</td></tr>';
                    html += '<tr><td width="150" class="pl55">充值服务器：</td><td width="406">' + result.ServerName + '</td></tr>';
                    html += '<tr><td width="150" class="pl55">游戏币数量：</td><td width="406">' + result.GameCurrencyAmount + result.GameCurrencyUnit + '</td></tr>';
                    html += '<tr><td width="150" class="pl55">支付手续费：</td><td width="406" class="orange1">￥' + result.ServiceCharge + '</td></tr>';
                    html += '<tr><td width="150" class="pl55">返利金额：</td><td width="406" class="orange1">￥' + result.RebateAmount + '</td></tr>';
                    //html += '<tr><td width="150" class="pl55">赠送积分：</td><td width="406" class="orange1">' + result.Integral + '</td></tr>';
                    html += '<tr><td width="150" class="pl55">赠送礼包：</td><td width="406" class="orange1">' + result.GiftBag + '</td></tr>';
                    html += '<tr><td>&nbsp;</td><td><input type="button" value="确认" onclick="Pay.subPay();" class="gy_btn  btn  round fs18"><input type="button" value="修改" onclick="MessageBox.close();" class="gy_btn3 btn round fs18"></td></tr>';
                    html += "</div>";
                    //var page = $.layer({
                    //    type: 1,   //0-4的选择,
                    //    title: false,
                    //    border: [0],
                    //    closeBtn: [0, false],
                    //    shadeClose: true,
                    //    area: ['580px', '580px'],
                    //    bgcolor: '',
                    //    page: {
                    //        html: html
                    //    }
                    //});
                    layer.open({
                        type: 1,
                        title: false,
                        closeBtn: false,
                        shadeClose: true,
                        area: ['600px', '559px'],
                        skin: 'yourclass',
                        content: html
                    });
                }
                else {
                    alert(result.Info);
                }
            }
        });
    },
    subPay: function () {
        MessageBox.close();
        var payMode = $("[name='PayMode']").val();
        if (payMode == "14") {
            $.post("/pay/payorder", $("#form1").serialize(), function (result) {
                if (result.Success) {
                    Pay.showWeixinCode(result.Value);
                } else {
                    alert(result.Info);
                }
            });
        } else {
            $("#form1").submit();
        }
    },
    showWeixinCode: function (url) {
        var html = '<div class="order shadow2" style="width:350px;"><div class="order_bt" style="width:350px;"><h3 style="width:350px;"><b>微信扫码支付</b><a href="javascript:void(0);" onclick="MessageBox.close();"></a></h3></div>';
        html += '<div style="width:260px;height:280px;margin:30px auto 0px auto;"><img src="/common/getqrcode?url=' + encodeURI(url) + '"/></div>';
        html += '<div style="width:260px;margin:0px auto;padding-bottom:20px;"><img src="/static/images/weixinpaytxt.png"/></div>';
        html += '</div>';

        layer.open({
            type: 1,
            title: false,
            closeBtn: false,
            shadeClose: true,
            area: ['360', '450'],
            skin: 'yourclass',
            content: html
        });
    },
    //初始化游戏
    initGame: function (gid, sid) {
        $.post("/common/querygame", { gameID: gid }, function (result) {
            if (result) {
                //设置兑换表单信息
                Pay.gameRate = result.ExchangeRate;
                Pay.setExchangeForm(result.GameID, result.Name, result.GameCurrencyUnit, result.ExchangeRate);
                Pay.showRatio();
                var info = result.Name;
                $("#gameSet").children("a").html(result.Name);
                $.post("/common/queryserverbyid", { serverID: sid }, function (data) {
                    if (data) {
                        $("[name='ServerID']").val(data.GameServerID);
                        $("[name='ServerName']").val(data.Name);
                        info += "   " + data.Name;
                        if (result.Name && data.Name) {
                            $("#gameSet").children("a").html(info);
                        }
                    }
                });
            }
        });
    },
    //初始化支付菜单
    initPayMenu: function () {
        $("#payMenu li").click(function () {
            var $self = $(this);
            var index = $self.index();

            if (index == 3) {
                $("#bank_list").show();
            } else {
                $("#bank_list").hide();
            }

            $("#exAmount").html("");
            var payMode = $.trim($self.attr("paymode"));
            var instCode = $.trim($self.attr("instcode"));
            var instName = $.trim($self.attr("instname"));
            Pay.payRate = $.trim($self.attr("rate"));

            Pay.showRatio();
            $("[name='PayMode']").val(payMode);
            $("[name='PayInstitutionCode']").val(instCode);
            $("[name='PayInstitutionName']").val(instName);

            //若使用支付宝支付，则不需要一下参数
            if ($self.index() != 0) {
                var payType = $.trim($self.attr("paytype"));
                var payChannel = $.trim($self.attr("paychannel"));
                $("[name='PayType']").val(payType);
                $("[name='PayChannel']").val(payChannel);
                $("[name=PayBank]").attr("checked", false);
            }

            $self.siblings().children("a").removeClass("curent");
            $self.children("a").addClass("curent");
            $("#bottom_tips").children("div").eq(index).show();
            $("#bottom_tips").children("div").eq(index).siblings("div").hide();
            $("[data='AmountList']").eq(index).show().siblings().hide();
        });
    },
    setPayBank: function (code) {
        $("[name='PayInstitutionCode']").val(code);
    },
    setPayMenu: function (payChannel, instCode) {
        if (payChannel == "" || payChannel == null || payChannel == undefined) {
            $("#payMenu li").eq(0).click();
            $("[data='AmountList']").eq(0).show().siblings().hide();
        } else {
            var idx = parseInt(this.payType[payChannel]);
            $("#payMenu li").eq(idx).click();
            if (payChannel == "19") {
                $.each($("[name=PayBank]"), function (index, value) {
                    if ($(value).attr("code") == instCode) {
                        $(value).attr("checked", true);
                    }
                });
            }
        }
    },
    showRatio: function () {
        var exAmount = Pay.exchangeAmount();
        if (!isNaN(exAmount)) {
            $("#exRate").html("(兑换比例: 1:" + exAmount + ")");
        } else {
            $("#exRate").html("");
        }
    },
    initAmountList: function () {
        $("[name='BuyAmount']").removeAttr("checked");
        $("#exAmount").html("");
    },
    //查询订单状态
    queryOrderState: function (orderID) {
        $.post("/Pay/QueryOrder", { id: orderID }, function (result) {
            if (result) {
                switch (parseInt(result.State)) {
                    case 100:
                        $("#charge_text").html('<p>您的订单尚未付款，请尽快付款，如有疑问，请联系客服</p>');
                        break;
                    case 101:
                        $("#charge_text").html('<p>您的订单已经充值成功，如有疑问，请联系客服</p>');
                        break;
                    case 102:
                        $("#charge_text").html('<p>您的订单正在充值中，请耐心等待，如有疑问，请联系客服</p>');
                        break;
                    case 103:
                        $("#charge_text").html('<p>由于网络波动，您的订单状态可疑，若未到账，请联系客服进行处理</p>');
                        break;
                    case 201:
                        $("#charge_text").html('<p>您的订单充值失败，我们会尽快为您退款，如有疑问，请联系客服</p>');
                        break;
                    default:
                        $("#charge_text").html('<p>由于网络波动，您的订单状态可疑，若未到账，请联系客服进行处理</p>');
                        break;

                }
            }
        });
    },

    setExchangeForm: function (gid, gname, curUnit, exRate) {
        $("[name='GameID']").val(gid);
        $("[name='GameName']").val(gname);
        $("[name='GameCurrencyUnit']").val(curUnit);
        $("[name='ExchangeRate']").val(exRate);
        $("#curUnit").html(curUnit);
    },
    exchangeAmount: function () {
        var amount = (Pay.gameRate * (1 - Pay.payRate)) + (Pay.gameRate * Pay.discount);
        return amount.toFixed(2);
    },
    resetChangeInfo: function () {
        $("[name='BuyAmount']").attr("checked", false);
        $("#exAmount").html("");
        $("#curUnit").html("");
        $("#exRate").html("(兑换比例:)");
    },
    chooseOtherMoney: function (obj) {
        Pay.getDiscount();
        if (Pay.validGameInfo()) {
            $("#exAmount").html("");
            $(obj).parent().prev().children().children().attr("checked", true);
        }
    },
    setOtherMoney: function (obj) {
        Pay.getDiscount();
        if (Pay.validGameInfo()) {
            $('#exAmount').html('');
            $(obj).parent().parent().next().children("input").focus();
        }
    },
    //验证是否选择了需要充值的游戏
    validGameInfo: function () {
        var game = $("[name='GameID']").val();
        var rechargeMode = $("[name='RechargeMode']:checked").val();
        if (game == "" || game == null || game == undefined) {
            if (rechargeMode == '1') {
                this.chooseGame();
                $("[name='BuyAmount']").attr("checked", false);
                return false;
            }
        }

        return true;
    },
    getDiscount: function () {
        var val = $("[name='TargetAccount']").val();
        if (val != Pay.targetAccount) {
            Pay.targetAccount = val;
            MessageBox.loading("正在验证...");

            $.ajaxSetup({
                async: false
            });
            $.post("/Common/GetOrderDiscount", { playerName: val }, function (result) {
                if (result != null && result != undefined) {
                    Pay.discount = result;
                }
                //重新显示兑换比例
                Pay.showRatio();
                setTimeout(function () {
                    MessageBox.close();
                }, 500);

                $.ajaxSetup({
                    async: true
                });
            });
        }
    },
    //初始化数据
    initData: function (channel, instCode, gameID, serverID) {

        MessageBox.loading("请稍后...");
        Pay.initPayMenu();
        Pay.setPayMenu(channel, instCode);
        Pay.initGame(gameID, serverID);

        //var timer = setInterval(function () {
        //    if (Pay.payRate != undefined && Pay.gameRate != undefined) {
        //        clearInterval(timer);
        //        MessageBox.close();
        //    }
        //}, 500);

        setTimeout(function () { MessageBox.close(); }, 500);
    }
}

var Task = {
    taskIndex: undefined,
    getTask: function (idx, pid, tid, step, obj) {
        Task.taskIndex = step;
        $.post("/Home/PhoneIsValid", { playerID: pid }, function (result) {
            if (result.Success) {
                //如果手机已认证，则验证玩家是否具有领取任务的资格
                $.post("/Home/IsCanJoinTask", { playerID: pid, taskStepID: tid }, function (data) {
                    if (data.Success) {
                        //可以领取任务
                        $.post("/Home/PlayerTakeTask", { stepID: tid, step: step }, function (dealResult) {
                            if (dealResult.Success) {
                                if (parseInt(step) == 1) {
                                    $(obj).removeClass().addClass("i03");
                                    $(obj).attr("onclick", "Task.takeTask('" + dealResult.Value + "','" + step + "');");
                                    //var fuyiWindow = window.open('_blank');
                                    //fuyiWindow.location = 'http://jrq.com/register?channel=web_shuwang&platform=wealth';
                                    return true;
                                } else {
                                    Task.showStepResult(obj, dealResult.Value, step);
                                    return false;
                                }
                            } else {
                                alert(dealResult.Info);
                                return false;
                            }
                        });
                    } else {
                        //Task.showBlock("step" + step + "_suc");
                        var tar_id = "step" + step + "_suc";
                        $("#" + tar_id + " h2").html("您已经完成过该任务啦~");
                        Task.showBlock(tar_id);
                        return false;
                    }
                });

            } else {
                $("#reg_container").hide();
                $("#arrow").removeClass("r_ind0").removeClass("r_ind1").removeClass("r_ind2");
                $("#arrow").addClass("r_ind" + idx);
                Task.showBlock("reg_container");
                return false;
            }
        });
    },
    sendCode: function () {
        var phone = $.trim($("[name='PhoneNumber']").val());

        var seconds = 60;

        $("#codeGetor").attr("disabled", true);
        $("#codeGetor").val(seconds + "秒后可重新发送");
        var timer = setInterval(function () {
            seconds--;
            if (seconds <= 0) {
                $("#codeGetor").val("获取验证码");
                $("#codeGetor").attr("disabled", false);
                clearInterval(timer);
            } else {
                $("#codeGetor").val(seconds + "秒后可重新发送");
            }
        }, 1000);

        $.post("/home/sendverifycode", { phoneNumber: phone }, function (result) {
            if (!result.Success) {
                alert(result.Info);
                $("#codeGetor").val("获取验证码");
                $("#codeGetor").attr("disabled", false);
                clearInterval(timer);
            }
        });
    },
    setCodeTimer: function (isStop) {
        var seconds = 60;

        $("#codeGetor").attr("disabled", true);
        $("#codeGetor").val(seconds + "秒后可重新发送");
        var timer = setInterval(function () {
            seconds--;
            if (seconds <= 0) {
                $("#codeGetor").val("获取验证码");
                $("#codeGetor").attr("disabled", false);
                clearInterval(timer);
            } else {
                $("#codeGetor").val(seconds + "秒后可重新发送");
            }
        }, 1000);

        if (isStop && timer != undefined) {
            alert(timer);
            clearInterval(timer);
            return false;
        }
    },
    bindPhone: function () {
        var phone = $.trim($("[name='PhoneNumber']").val());
        var code = $.trim($("[name='VerifyCode']").val());
        $.post("/Home/BindingPhoneResult", { phoneNumber: phone, code: code }, function (result) {
            if (result.Success) {
                if (Task.taskIndex == 1) {
                    $("#step1_pass").attr("href", "http://jrq.com/register?channel=web_shuwang&platform=wealth");
                    alert("绑定成功，请尽快完成注册");
                    //var fuyiWindow = window.open('_blank');
                    //fuyiWindow.location = 'http://jrq.com/register?channel=web_shuwang&platform=wealth';
                } else if (Task.taskIndex == 2) {
                    alert("绑定成功，安卓用户请直接扫码下载，IOS用户请先完成1元任务，再从AppStore下载并登录金融圈，否则不能完成任务");
                    Task.showBlock("step2_Qr");
                } else if (Task.taskIndex == 3) {
                    alert("绑定成功，请在完成1元和4元任务后，购买金融圈任意理财产品，2天后即可获得任务奖金");
                    Task.showBlock("step3_intro");
                }

                $('#reg_container').hide();
            } else {
                alert(result.Info);
            }
        });
    },
    showStepResult: function (obj, rid, step) {
        $(obj).removeClass().addClass("i03");
        $(obj).attr("onclick", "Task.takeTask('" + rid + "','" + step + "');");
        if (step == 2) {
            Task.showBlock("step2_Qr");
            return false;
        }

        if (step == 3) {
            Task.showBlock("step3_intro");
            return false;
        }
    },
    takeTask: function (rid, step, obj) {
        $("#step1_pass").attr("href", "javascript:void(0);");
        $("#r_ind").removeClass("r_ind0").removeClass("r_ind1").removeClass("r_ind2");
        $("#r_ind").addClass("r_ind" + (step - 1));
        var targetLink = $(obj).attr("onclick");
        $(obj).removeAttr("onclick");
        $("#arr_msg").html("红包验证中....");
        Task.showBlock("arrow");
        var arr_msg = "";
        $.post("/Home/IssueTask", { recordID: rid }, function (result) {
            $(obj).attr("onclick", targetLink);
            if (result.Success) {
                $("#arrow").hide();
                Task.showTaskSuc(step);
            } else {
                if (step == 1) {
                    if (result.Info.indexOf("尚未完成") > 0) {
                        //var fuyiWindow = window.open('_blank');
                        //fuyiWindow.location = 'http://jrq.com/register?channel=web_shuwang&platform=wealth';
                        $("#arr_msg").html(result.Info + '<br/><a href="http://jrq.com/register?channel=web_shuwang&platform=wealth" target="_blank">点此完成注册</a>');
                    } else {
                        $("#arr_msg").html(result.Info);
                    }
                } else if (step == 2) {
                    //如果为任务2，则需要展示出下载二维码，以便为玩家再次提供下载途径
                    Task.showBlock("step2_Qr");
                    alert(result.Info);
                } else {
                    $("#arr_msg").html(result.Info);
                }
            }
        });
    },
    showTaskSuc: function (step) {
        if (step == 1) {
            Task.showBlock("step1_suc");
        }
        if (step == 2) {
            Task.showBlock("step2_suc");
        }
        if (step == 3) {
            Task.showBlock("step3_suc");
        }
    },
    showBlock: function (id) {
        var blocks = new Array("reg_container", "step1_suc", "step2_Qr", "step2_suc", "step3_intro", "arrow", "step3_suc");
        $.each(blocks, function (index, value) {
            if (value == id) {
                $("#" + value).show();
            } else {
                $("#" + value).hide();
            }
        });
    },
    completeStep2: function () {
        var obj = $("#step2_pass");
        var rid = obj.attr("record");
        Task.takeTask(rid, 2, obj);
    },
    validPhoneBind: function (pid) {
        $.post("/Home/PhoneIsValid", { playerID: pid }, function (result) {
            if (result.Success) {
                $("#step1_pass").attr("href", "http://jrq.com/register?channel=web_shuwang&platform=wealth");
            }
        });
    }
}